package com.galengao.rabbitmq.util;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeoutException;

/**
 * 抽取rabbitmq的工具类
 */
@Slf4j
public class RabbitmqUtils {

    private static final Properties properties = PropertiesLoader.getProps("rabbitmq.properties");
    /**
     * 队列名称
     */
    public static final String QUEUE_NAME;
    /**
     * 交换机名称
     */
    public static final String EXCHANGE_NAME;
    /**
     * 路由key
     */
    public static final String ROUTE_KEY;

    static {
        EXCHANGE_NAME = properties.getProperty("rabbitmq.exchangeName");
        QUEUE_NAME = properties.getProperty("rabbitmq.queueName");
        ROUTE_KEY = properties.getProperty("rabbitmq.routeKey");
    }

    /**
     * 获取rabbitmq连接工厂
     * @see com.rabbitmq.client.ConnectionFactory
     * @return 返回rabbitmq ConnectionFactory
     */
    public static ConnectionFactory connectionFactory() {
        // 1. 创建连接工厂

        ConnectionFactory connectionFactory = new ConnectionFactory();
        // 设置连接属性
        connectionFactory.setHost(properties.getProperty("rabbitmq.host"));
        connectionFactory.setPort(Integer.parseInt(properties.getProperty("rabbitmq.port")));
        connectionFactory.setUsername(properties.getProperty("rabbitmq.username"));
        connectionFactory.setPassword(properties.getProperty("rabbitmq.password"));
        log.info("create connectionFactory success:{}",connectionFactory);
        return connectionFactory;
    }

    /**
     * 获取 rabbitmq连接
     * @see  com.rabbitmq.client.Connection
     * @see com.rabbitmq.client.ConnectionFactory
     * @param connectionFactory 连接工厂
     * @return Connection
     * @throws IOException IOException
     * @throws TimeoutException IOException
     */
    public static Connection getConnection(ConnectionFactory connectionFactory) throws IOException, TimeoutException {
        return connectionFactory.newConnection();
    }

    /**
     * 获取rabbitmq连接通道
     * @see com.rabbitmq.client.Channel
     * @see  com.rabbitmq.client.Connection
     * @return 获取rabbitmq连接通道
     * @throws IOException  IOException
     */
    public static Channel getChannel(Connection connection) throws IOException {
        return connection.createChannel();
    }
}
